<template>
  <div id="modal">
    <commonModal ref="myModal" width="40%" title="志愿选择">
      <template #default>
        <a-form ref="formRef" :model="form">
          <a-form-item ref="name" :label="v.label" name="name" v-for="(v, i) in selectList" :key="v.label">
            <div class="error-msg ml-70" v-show="startFlag && regList && regList[i] < 3">
              {{ v.label }}为必选项
            </div>
            <div class="item-wrap">
              <template v-for="(item, idx) in v.columns">
                <a-form-item-rest>
                  <a-select @change="handleSelectChange(v, item, form[`value${i + 1}-${idx + 1}`])"
                    v-model:value="form[`value${i + 1}-${idx + 1}`]" :placeholder="item.placeholder" allowClear>
                    <a-select-option :value="el.value" :disabled="el.disabled" v-for="el in item.options"
                      :key="el.text">{{ el.text }}</a-select-option>
                  </a-select>
                </a-form-item-rest>
              </template>
            </div>
          </a-form-item>
          <a-form-item label="地区是否接受调剂" name="area">
            <div class="error-msg" v-show="!form.area && startFlag">此项为必填</div>
            <a-radio-group v-model:value="form.area">
              <a-radio :value="item.value" v-for="item in radioOptions" :key="item.label">{{
                item.label
              }}</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="科目是否接受调剂" name="subject">
            <div class="error-msg" v-show="!form.subject && startFlag">此项为必填</div>
            <a-radio-group v-model:value="form.subject">
              <a-radio :value="item.value" v-for="item in radioOptions" :key="item.label">{{
                item.label
              }}</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="年级是否接受调剂" name="grade">
            <div class="error-msg" v-show="!form.grade && startFlag">此项为必填</div>
            <a-radio-group v-model:value="form.grade">
              <a-radio :value="item.value" v-for="item in radioOptions" :key="item.label">{{
                item.label
              }}</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-form>
        <div class="tip">
          每人仅允许填写一次志愿，请根据实际情况填写，提交成功后无法自助修改。如有特殊情况请及时与对应HR沟通。
        </div>
        <div class="btn-area">
          <a-button @click="myModal.show = false">取消</a-button>
          <a-button type="primary" @click="confirm">确认</a-button>
        </div>
      </template>
    </commonModal>
  </div>
  <FinishModal v-if="showFinishModal" @closeFinishModal="showFinishModal = false"></FinishModal>
</template>

<script setup lang="ts">
import { message } from "ant-design-vue"
import commonModal from '../index/commonModal.vue';
import { data } from "./data"
import FinishModal from "../index/FinishModal.vue";
const myModal = ref<typeof commonModal>(commonModal);
import { useStore } from "../../store/index.ts";
import apis from "../../api/index.ts"
const { saveUservolunteer } = apis
const store = useStore()
const show = () => {
  myModal.value.show = true;
};

const form = ref<any>({
  subject: '',
  area: '',
  grade: '',
});
const radioOptions = ref([
  { label: '是', value: 1 },
  { label: '否', value: 2 },
]);

const regList = ref<number[]>();
const showFinishModal = ref<boolean>(false);
const columns = ref<Columns[]>([
  // 第一列
  {
    key: 'l1',
    value: '',
    placeholder: '请选择地区',
    options: [
      {
        text: '合肥', value: '合肥'
      },
      { text: '芜湖', value: '芜湖' },
      { text: '安庆', value: '安庆' },
      { text: '马鞍山', value: '马鞍山' },
      { text: '新加坡', value: '新加坡' },

    ],
  },
  // 第二列
  {
    key: 'l2',
    value: '',
    placeholder: '请选择科目',
    options: [
      { text: '数学', value: '数学' },
      { text: '英语', value: '英语', },
      { text: '化学', value: '化学', },
      { text: '物理', value: '物理', },
    ],
  },
  {
    key: 'l3',
    value: '',
    placeholder: '请选择年级',
    options: [
      { text: '1-2年级', value: '1-2年级' },
      { text: '3-6年级', value: '3-6年级' },
      { text: '初中', value: '初中', },
      { text: '高中', value: '高中', },
    ],
  },
]);

interface Columns {
  key: string;
  value: string;
  placeholder: string;
  options: Options[];
}
interface SelectItem {
  label: string;
  columns: Columns[];
  id: number;
}
interface Options {
  text: string;
  value: string | number;
  disabled?: boolean;
  usableList?: any
}
const selectList = ref<SelectItem[]>([
  { label: '第一志愿', id: 1, columns: JSON.parse(JSON.stringify(columns.value)) },
  { label: '第二志愿', id: 2, columns: JSON.parse(JSON.stringify(columns.value)) },
  { label: '第三志愿', id: 3, columns: JSON.parse(JSON.stringify(columns.value)) },
]);



function updateRegionOptions(selectedRegion, selectedSubject, selectedGrade, options, v: SelectItem) {
  for (const option of options) {
    if (option.value === '') continue;
    const region = option.value;
    let disabled = false;
    if (selectedSubject && !data[region][selectedSubject]) {
      disabled = true;
    }
    if (
      selectedGrade &&
      !Object.values(data[region]).some((grades: any) => grades.includes(selectedGrade))
    ) {
      disabled = true;
    }
    option.disabled = disabled;
  }
  v.columns[0].options = options
}

function updateSubjectOptions(selectedRegion, selectedSubject, selectedGrade, options, v: SelectItem) {
  for (const option of options) {
    if (option.value === '') continue;
    const subject = option.value;
    let disabled = false;
    if (selectedRegion && !data[selectedRegion][subject]) {
      disabled = true;
    }
    if (
      selectedGrade &&
      !Object.values(data).some((subjects) => subjects[subject]?.includes(selectedGrade))
    ) {
      disabled = true;
    }
    option.disabled = disabled;
  }
  v.columns[1].options = options
}

function updateGradeOptions(selectedRegion, selectedSubject, selectedGrade, options, v: SelectItem) {
  const gradeSelect = document.getElementById('grade');
  for (const option of options) {
    if (option.value === '') continue;
    const grade = option.value;
    let disabled = false;
    if (
      selectedRegion &&
      !Object.values(data[selectedRegion]).some((grades: any) => grades.includes(grade))
    ) {
      disabled = true;
    }
    if (
      selectedSubject &&
      !Object.values(data).some((subjects) => subjects[selectedSubject]?.includes(grade))
    ) {
      disabled = true;
    }
    option.disabled = disabled;
  }
  v.columns[2].options = options
}


const validate = (v: SelectItem, item: Columns, key: string, value: string) => {
  const changed = item.key;
  const region = form.value[key + '-1'];
  const subject = form.value[key + '-2'];
  const grade = form.value[key + '-3'];
  const regionOptions = columns.value[0].options;
  const subjectOptions = columns.value[1].options;
  const gradeOptions = columns.value[2].options
  console.log(v)
  if (changed === 'l1' || changed === 'l2') {
    updateRegionOptions(region, subject, grade, regionOptions, v);
    updateSubjectOptions(region, subject, grade, subjectOptions, v);
  }
  if (changed === 'l1' || changed === 'l3') {
    updateRegionOptions(region, subject, grade, regionOptions, v);
    updateGradeOptions(region, subject, grade, gradeOptions, v);
  }
  if (changed === 'l2' || changed === 'l3') {
    updateSubjectOptions(region, subject, grade, subjectOptions, v);
    updateGradeOptions(region, subject, grade, gradeOptions, v);
  }
};

const handleSelectChange = (v: SelectItem, item: Columns, value) => {
  console.log(v)
  validate(v, item, `value${v.id}`, value);
};

const getFormLen = (val: RegExp): number => {
  const validValue1Keys = Object.keys(form.value).filter((key) => {
    const value = form.value[key];
    return val.test(key) && value;
  });
  return validValue1Keys.length;
};
const juage = () => {
  const list: number[] = [];
  [/^value1/, /^value2/, /^value3/].forEach((el: RegExp) => {
    list.push(getFormLen(el));
  });
  regList.value = list;
};
const startFlag = ref<boolean>(false);


const transformData = (data) => {
  const result = [];
  const temp: any = {};

  for (const [key, value] of Object.entries(data)) {
    const [item, subItem] = key.split('-');
    const map = {
      '1': "area",
      "2": "subject",
      '3': "grade"
    }
    if (!temp[item]) {
      temp[item] = {};
    }
    if (map[subItem]) {
      temp[item][map[subItem]] = value;
    }

  }
  for (const [key, value] of Object.entries(temp)) {
    const val = value as any
    if (val?.area) {
      result.push(value);
    }
  }
  return result;
}


const confirm = async () => {
  juage();
  startFlag.value = true;
  const isPass =
    regList.value?.every((el) => el === 3) && Object.values(form.value).every((item) => !!item);
  console.log(isPass);
  if (!isPass) return;

  console.log(form.value);

  const transformedData = transformData(form.value);
  console.log(transformedData, 'transformedData')
  const { subject, grade, area } = form.value
  const param = {
    subjectIsAdjust: subject,
    gradeIsAdjust: grade,
    areaIsAdjust: area,
    volunteerList: JSON.stringify(transformedData),
    resumesId: "1"
  };
  console.log(param, 'param')
  const data: any = await saveUservolunteer(param);
  if (data && data.code === '10000') {
  } else {
    message.error(data.msg)
  }
  // myModal.value.show = false;
  // await nextTick();
  // showFinishModal.value = true;
};
watch(form.value, () => {
  juage();
});

watch(showFinishModal, async (val) => {
  const el = document.querySelector('body') as HTMLBodyElement;
  el.style.overflowY = val ? 'hidden' : 'auto';
});

defineExpose({
  show,
});
</script>
<style lang="scss" scoped>
.item-wrap {
  display: flex;
  gap: 20px;
}

.tip {
  font-weight: 400;
  font-size: 14px;
  color: #b3c0c8;
  line-height: 28px;
}

.btn-area {
  display: flex;
  justify-content: center;
  gap: 40px;
  margin-top: 29px;
}

.error-msg {
  left: -125px;
  top: 30px;
  position: absolute;
  font-size: 12px;
  color: red;
}

.ml-70 {
  margin-left: 56px;
}
</style>
